package controllers

import (
	"../../../deps/lessgo/pagelet"
	"../../../deps/lessgo/utils"
	"../../../deps/lessgo/utilx"
	"../../conf"
	"../../state"
	"../../store"
	"../schema"
	"fmt"
	"io"
	"strings"
)

type Self struct {
	*pagelet.Controller
}

func (c Self) InfoAction() {

	c.AutoRender = false

	var rsp struct {
		ResponseJson
		Data schema.ServPeer `json:"data"`
	}
	rsp.ApiVersion = apiVersion
	rsp.Status = 400
	rsp.Message = "Bad Request"

	defer func() {
		if rspj, err := utils.JsonEncode(rsp); err == nil {
			io.WriteString(c.Response.Out, rspj)
		}
	}()

	rsp.Data.KeeperId = store.Cmd("HGET", "sys:keeper", "id").String()
	rsp.Data.KeeperName = store.Cmd("HGET", "sys:keeper", "name").String()

	rsp.Data.Id = conf.Config.HostId
	rsp.Data.Proto = "http"
	rsp.Data.Addr = conf.Config.KeeperAddr
	rsp.Data.Port = conf.Config.Port
	rsp.Data.Uptime = utilx.TimeZoneFormat(state.Uptime, "Local", "atom")

	rsp.Status = 200
	rsp.Message = ""
}

func (c Self) SetupInitAction() {

	c.AutoRender = false

	var rsp struct {
		ResponseJson
	}
	rsp.ApiVersion = apiVersion
	rsp.Status = 400
	rsp.Message = "Bad Request"

	defer func() {
		if rspj, err := utils.JsonEncode(rsp); err == nil {
			io.WriteString(c.Response.Out, rspj)
		}
	}()

	keeperid := store.Cmd("HGET", "sys:keeper", "id").String()
	if len(keeperid) > 0 {
		rsp.Message = fmt.Sprintf("The Peer (IP: %s) Have been configured, Can not be used again", conf.Config.KeeperAddr)
		return
	}

	var req struct {
		Data schema.ServSetupInit `json:"data"`
	}

	if len(c.Request.RawBody) == 0 {
		return
	}
	err := utils.JsonDecode(c.Request.RawBody, &req)
	if err != nil {
		return
	}

	item := map[string]string{
		"id":   req.Data.KeeperId,
		"name": req.Data.KeeperName,
	}
	r := store.Cmd("HMSET", "sys:keeper", item)
	if r.Err != nil {
		return
	}

	for _, v := range req.Data.Peers {

		hostid := strings.ToLower(v.Id)
		pitem := map[string]string{
			"hostid": hostid,
			"proto":  v.Proto,
			"addr":   v.Addr,
			"port":   v.Port,
			"status": "1",
		}

		store.Cmd("HMSET", "sys:peers:"+hostid, pitem)
	}

	rsp.Status = 200
	rsp.Message = ""
}
